import App from '@/App.vue'
import { router } from '../index'
import { store } from '../store'
import WujieVue from 'wujie-vue2'

import { variables } from '../styles/index.js'

const globalComponents = {},
  globalPlugins = {}

export {
  globalComponents, globalPlugins
}

const install = (Vue) => {
  if (install.installed) {
    return
  }

  // 注册全局组件
  Object.keys(globalComponents).map(key => {
    Vue.component(key, globalComponents[key])
  })

  Vue.config.productionTip = false

  new Vue({
    router,
    store,
    ...globalPlugins,
    watch: {
      $route () {
        if (this.$route.meta?.subapp?.alive) {
          // 子应用保活模式下，需要以通讯方式改变子应用路由
          WujieVue.bus.$emit(`${this.$route.meta.subapp?.name}-route-change`, `/${this.$route.params.path}`, { query: this.$route.query })
        }
      },
      fontSize (val) {
        // 设置 "html" 标签的 font-size
        document.documentElement.style.setProperty('font-size', this.fontSize)
      }
    },
    computed: {
      fontSize () {
        return this.$store.getTheme('fontSize', '14px')
      }
    },
    created () {
      // 设置 "html" 标签的 font-size
      document.documentElement.style.fontSize = `14px`
      const cssVars = document.createElement('style')
      cssVars.type = 'text/css'
      cssVars.id = 'css-vars'
      const vars = Object.keys(variables).map(key => `${key}: ${variables[key]};`).join('\n')
      cssVars.innerHTML = `:root {
        ${vars}
      }`
      document.documentElement.appendChild(cssVars)
    },
    render: h => h(App)
  }).$mount('#app')
}

export default {
  install
}
